package com.ldapauth.persistence.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;

import com.ldapauth.abstracts.CommonTablesAbstracts;
import com.ldapauth.exception.BusinessException;
import com.ldapauth.persistence.service.CommonTablesService;
import com.ldapauth.pojo.dto.CommonDeleteTableDTO;
import com.ldapauth.pojo.dto.CommonInsertTableDTO;
import com.ldapauth.pojo.dto.CommonSelectTableDTO;
import com.ldapauth.pojo.dto.CommonUpdateTableDTO;
import com.ldapauth.pojo.dto.action.TableBodyDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CommonTablesServiceImpl extends CommonTablesAbstracts implements CommonTablesService {


    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public List<Map<String,Object>> select(CommonSelectTableDTO commonSelectTableDTO) {
        try {
            //构建查询列
            String selectColumns = buildSelectCoulunm(commonSelectTableDTO.getSelectColumnNames());
            StringBuilder sqlStringBuilder = new StringBuilder("select " + selectColumns + " from " + commonSelectTableDTO.getTableName());
            List<Map<String, Object>> maps = new ArrayList<>();
            //获取查询条件
            if (CollectionUtil.isNotEmpty(commonSelectTableDTO.getWheres())) {
                sqlStringBuilder.append(" where ");
                //获取查询字段
                List<String> fieldNames = commonSelectTableDTO.getWheres().stream().map(TableBodyDTO::getColumnName).collect(Collectors.toList());
                //查询字段值
                List<String> fieldValues = commonSelectTableDTO.getWheres().stream().map(TableBodyDTO::getColumnValue).collect(Collectors.toList());
                int i = 0;
                for (String name : fieldNames) {
                    if (i == 0) {
                        sqlStringBuilder.append(" " + name + "=?");
                    } else {
                        sqlStringBuilder.append(" and " + name + "=?");
                    }
                    i++;
                }
                Object[] objects = fieldValues.toArray();
                log.info("build sql :{}", sqlStringBuilder.toString());
                log.info("build param :{}", StrUtil.join(",",objects));
                maps = jdbcTemplate.queryForList(sqlStringBuilder.toString(), objects);
            } else {
                log.info("build select sql :{}", sqlStringBuilder.toString());

                maps = jdbcTemplate.queryForList(sqlStringBuilder.toString());
            }
            return maps;
        } catch (Exception e){
            log.error("error",e);
            throw new BusinessException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "操作异常，具体消息："+e.getMessage());
        }
    }


    @Override
    public Boolean insert(CommonInsertTableDTO commonInsertTableDTO) {
        try {
            List<String> fieldNames = commonInsertTableDTO.getBody().stream().map(TableBodyDTO::getColumnName).collect(Collectors.toList());
            //查询字段值
            List<String> fieldValues = commonInsertTableDTO.getBody().stream().map(TableBodyDTO::getColumnValue).collect(Collectors.toList());

            String setColumns = buildInsertSetColumns(fieldNames,0);
            String setColumnsValue = buildInsertSetColumns(fieldNames,1);

            //构建插入字段
            StringBuilder sqlStringBuilder = new StringBuilder("insert into "+commonInsertTableDTO.getTableName()+"("+setColumns+") values("+setColumnsValue+") ");

            Object[] objects = fieldValues.toArray();
            log.info("build sql :{}", sqlStringBuilder.toString());
            log.info("build param :{}", StrUtil.join(",",objects));
            jdbcTemplate.update(sqlStringBuilder.toString(), objects);
            return true;

        } catch (Exception e){
            log.error("error",e);
            throw new BusinessException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "操作异常，具体消息："+e.getMessage());
        }
    }

    @Override
    public Boolean update(CommonUpdateTableDTO commonUpdateTableDTO) {
        try {
            //获取更新字段
            List<String> updateFieldNames = commonUpdateTableDTO.getBody().stream().map(TableBodyDTO::getColumnName).collect(Collectors.toList());
            //获取更新字段值
            List<String> updateFieldValues = commonUpdateTableDTO.getBody().stream().map(TableBodyDTO::getColumnValue).collect(Collectors.toList());
            //构建更新字段
            String setColumns = buildSetColumns(updateFieldNames);
            StringBuilder sqlStringBuilder = new StringBuilder("update "+commonUpdateTableDTO.getTableName()+" set "+setColumns);
            List<Map<String, Object>> maps = new ArrayList<>();

            //获取条件
            if (CollectionUtil.isNotEmpty(commonUpdateTableDTO.getWheres())) {
                sqlStringBuilder.append(" where ");
                //获取查询字段
                List<String> whereFieldNames = commonUpdateTableDTO.getWheres().stream().map(TableBodyDTO::getColumnName).collect(Collectors.toList());
                //查询字段值
                List<String> whereFieldValues = commonUpdateTableDTO.getWheres().stream().map(TableBodyDTO::getColumnValue).collect(Collectors.toList());
                int i = 0;
                for (String name : whereFieldNames) {
                    if (i == 0) {
                        sqlStringBuilder.append(" " + name + "=?");
                    } else {
                        sqlStringBuilder.append(" and " + name + "=?");
                    }
                    i++;
                }
                for (String value : whereFieldValues) {
                    updateFieldValues.add(value);
                }
                Object[] objects = updateFieldValues.toArray();
                log.info("build sql :{}", sqlStringBuilder.toString());
                log.info("build param :{}", StrUtil.join(",",objects));
                jdbcTemplate.update(sqlStringBuilder.toString(), objects);
                return true;
            } else {
                Object[] objects = updateFieldValues.toArray();
                log.info("build sql :{}", sqlStringBuilder.toString());
                log.info("build param :{}", StrUtil.join(",",objects));
                jdbcTemplate.update(sqlStringBuilder.toString());
                return true;
            }

        } catch (Exception e){
            log.error("error",e);
            throw new BusinessException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "操作异常，具体消息："+e.getMessage());
        }
    }

    @Override
    public Boolean delete(CommonDeleteTableDTO commonDeleteTableDTO) {
        try {
            //构建删除字段
            StringBuilder sqlStringBuilder = new StringBuilder("delete from "+commonDeleteTableDTO.getTableName());
            //获取条件
            if (CollectionUtil.isNotEmpty(commonDeleteTableDTO.getWheres())) {
                sqlStringBuilder.append(" where ");
                //获取查询字段
                List<String> whereFieldNames = commonDeleteTableDTO.getWheres().stream().map(TableBodyDTO::getColumnName).collect(Collectors.toList());
                //查询字段值
                List<String> whereFieldValues = commonDeleteTableDTO.getWheres().stream().map(TableBodyDTO::getColumnValue).collect(Collectors.toList());
                int i = 0;
                for (String name : whereFieldNames) {
                    if (i == 0) {
                        sqlStringBuilder.append(" " + name + "=?");
                    } else {
                        sqlStringBuilder.append(" and " + name + "=?");
                    }
                    i++;
                }
                Object[] objects = whereFieldValues.toArray();
                log.info("build sql :{}", sqlStringBuilder.toString());
                log.info("build param :{}", StrUtil.join(",",objects));
                jdbcTemplate.update(sqlStringBuilder.toString(), objects);
                return true;
            } else {
                //不允许无条件进行删除表数据
                throw new BusinessException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "缺少删除条件");
            }

        } catch (Exception e){
            log.error("error",e);
            throw new BusinessException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "操作异常，具体消息："+e.getMessage());
        }
    }
}
